package by.dezhits.liltweets.content;

import org.json.JSONException;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import by.dezhits.liltweets.R;
import by.dezhits.liltweets.bo.Tweet;
import by.dezhits.liltweets.content.contract.TweetContract;
import by.dezhits.liltweets.db.DBHelper;

public class TweetsProvider extends ContentProvider {

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.ContentProvider#delete(android.net.Uri,
	 * java.lang.String, java.lang.String[])
	 */
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		dbHelper.deleteTweets(selection);
		getContext().getContentResolver().notifyChange(
				TweetContract.TweetsColumns.CONTENT_URI, null);
		return 0;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.ContentProvider#getType(android.net.Uri)
	 */
	@Override
	public String getType(Uri uri) {
		return TweetContract.TweetsColumns.CONTENT_TYPE;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.ContentProvider#insert(android.net.Uri,
	 * android.content.ContentValues)
	 */
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		String jsonData = values.getAsString(getContext().getString(R.string.data));
		try {
			Tweet tweet = new Tweet(jsonData);
			dbHelper.addTweet(tweet, DBHelper.TWEETS_TABLE);
			
		} catch (JSONException e) {
			//Ignored because result doesn't bother us while inserting
		}
		int tweetIndex = values.getAsInteger(getContext().getString(R.string.tweet_index));
		int tweetCount = values.getAsInteger(getContext().getString(R.string.tweet_count));
		if (tweetIndex == tweetCount - 1) {
			getContext().getContentResolver().notifyChange(
					TweetContract.TweetsColumns.CONTENT_URI, null);
		}
		return null;
	}

	private DBHelper dbHelper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.ContentProvider#onCreate()
	 */
	@Override
	public boolean onCreate() {
		dbHelper = new DBHelper(getContext(), null);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.ContentProvider#query(android.net.Uri,
	 * java.lang.String[], java.lang.String, java.lang.String[],
	 * java.lang.String)
	 */
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		Cursor tweets = dbHelper.getTweets(selection,selectionArgs,sortOrder);
		tweets.setNotificationUri(getContext().getContentResolver(), uri);
		return tweets;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.ContentProvider#update(android.net.Uri,
	 * android.content.ContentValues, java.lang.String, java.lang.String[])
	 */
	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		return 0;
	}

}
